package receiver;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.laoxinwen.app.R;

import activity.CommentActivity;
import activity.WebviewActivity;
import activity.NewsActivity;
import activity.ArticleActivity;
import activity.TopicActivity;
import bean.News;
import bean.wraper.DefaultIntWrapper;
import common.HttpCallBack;
import common.Requester;
import common.UserConfig;


public class PushReceiver extends BroadcastReceiver {
    private Context context;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        Bundle bundle = intent.getExtras();
        Log.d("GetuiSdkDemo", "onReceive() action=" + bundle.getInt("action"));
        switch (bundle.getInt(PushConsts.CMD_ACTION)) {
            case PushConsts.GET_MSG_DATA:
                // 获取透传数据
                // String appid = bundle.getString("appid");
                byte[] payload = bundle.getByteArray("payload");

                String taskid = bundle.getString("taskid");
                String messageid = bundle.getString("messageid");
                // smartPush第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
                boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
                System.out.println("第三方回执接口调用" + (result ? "成功" : "失败"));
                if (payload != null) {
                    String data = new String(payload);
                    try {
                        PushMsg pushMsg = JSONObject.parseObject(data, PushMsg.class);
                        sendNotification(pushMsg);
                    } catch (Exception e) {
                        Toast.makeText(context, "数据解析异常：" + data, Toast.LENGTH_LONG).show();
                    }

                }
                break;
            case PushConsts.GET_CLIENTID:
                // 获取ClientID(CID)
                // 第三方应用需要将CID上传到第三方服务器，并且将当前用户帐号和CID进行关联，以便日后通过用户帐号查找CID进行消息推送
                String cid = bundle.getString("clientid");
                UserConfig.setGetuiId(cid);
                if (UserConfig.isLogined()) {
                    Requester.bindGetui(cid, new HttpCallBack<DefaultIntWrapper>() {
                        @Override
                        public void onSucceed(DefaultIntWrapper data) {

                        }
                    });
                }
                break;
            case PushConsts.THIRDPART_FEEDBACK:
            /*String appid = bundle.getString("appid");
            String taskid = bundle.getString("taskid");
			String actionid = bundle.getString("actionid");
			String result = bundle.getString("result");
			long timestamp = bundle.getLong("timestamp");

			Log.d("GetuiSdkDemo", "appid = " + appid);
			Log.d("GetuiSdkDemo", "taskid = " + taskid);
			Log.d("GetuiSdkDemo", "actionid = " + actionid);
			Log.d("GetuiSdkDemo", "result = " + result);
			Log.d("GetuiSdkDemo", "timestamp = " + timestamp);*/
                break;
            default:
                break;
        }
    }

    private void sendNotification(PushMsg pushMsg) {
        Notification notify = new Notification();
        notify.flags = Notification.FLAG_AUTO_CANCEL;
        notify.icon = R.drawable.notification_icon;
        notify.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
        //		boolean isRunningInBackground = isRunningInBackground();

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        switch (pushMsg.getAction()) {
            case PushMsg.ACTION_NEWS:
                News news = new News();
                news.setId(pushMsg.getId());
                news.setTitle(pushMsg.getTitle());
                news.setSummary(pushMsg.getSummary());
                news.setTid(pushMsg.getTopicId());
                intent = NewsActivity.getIntent(context, news);
                break;
            case PushMsg.ACTION_TOPIC:
                intent.setClass(context, TopicActivity.class);
                intent.setAction(TopicActivity.ACTION_WITH_ID);
                intent.putExtra(TopicActivity.INTENT_KEY_NEWS_GROUP_ID, pushMsg.getId());
                break;
            case PushMsg.ACTION_COMMENT:
                intent = CommentActivity.getIntent(context, pushMsg.getTopicId(), pushMsg.getId(), pushMsg.getNewsId(), pushMsg.getArticleId());
                //                intent.setAction(TopicActivity.ACTION_WITH_ID);
                //                intent.putExtra(TopicActivity.INTENT_KEY_NEWS_GROUP_ID, pushMsg.getId());
                break;
            case PushMsg.ACTION_ARTICLE:
                News article = new News();
                article.setId(pushMsg.getId());
                article.setTitle(pushMsg.getTitle());
                article.setSummary(pushMsg.getSummary());
                article.setTid(pushMsg.getTopicId());
                intent = ArticleActivity.getIntent(context, article);
                break;
            case PushMsg.ACTION_URL:
                pushMsg.setId("" + System.currentTimeMillis());
                intent = WebviewActivity.getIntent(pushMsg.getTitle(), pushMsg.getUrl(), context);
                break;
        }
        PendingIntent contentIntent = PendingIntent.getActivity(context, pushMsg.getId().hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT);
        notify.tickerText = pushMsg.getTitle();
        notify.setLatestEventInfo(context, pushMsg.getTitle(), pushMsg.getSummary(), contentIntent);
        NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        nManager.notify(pushMsg.getId().hashCode(), notify);
    }


}

